

import React, { useState, useEffect, useRef } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Modal, Dimensions, Alert, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import Svg, { Circle, Line, Text as SvgText, G } from 'react-native-svg';
import Animated, { useSharedValue, useAnimatedStyle, withRepeat, withTiming, interpolate, } from 'react-native-reanimated';
import { GestureDetector, Gesture } from 'react-native-gesture-handler';
import styles from './styles';

interface ProcessNode {
  id: string;
  name: string;
  type: 'start' | 'end' | 'user';
  status: 'completed' | 'current' | 'pending' | 'future';
  assignee: string;
  time: string;
  result: string;
  comment: string;
  x: number;
  y: number;
}

interface ProcessConnection {
  from: string;
  to: string;
}

interface ProcessData {
  title: string;
  applicant: string;
  submitTime: string;
  currentNode: string;
  status: string;
  nodes: ProcessNode[];
  connections: ProcessConnection[];
}

const ApprovalFlowScreen: React.FC = () => {
  const router = useRouter();
  const params = useLocalSearchParams();
  const [isLoading, setIsLoading] = useState(true);
  const [processData, setProcessData] = useState<ProcessData | null>(null);
  const [isNodeTooltipVisible, setIsNodeTooltipVisible] = useState(false);
  const [selectedNode, setSelectedNode] = useState<ProcessNode | null>(null);
  const [tooltipPosition, setTooltipPosition] = useState({ x: 0, y: 0 });
  const [currentScale, setCurrentScale] = useState(1);
  const [currentTranslateX, setCurrentTranslateX] = useState(0);
  const [currentTranslateY, setCurrentTranslateY] = useState(0);
  
  const panRef = useRef({
    isDragging: false,
    lastTouchX: 0,
    lastTouchY: 0,
    lastTouchDistance: 0,
  });

  const pulseOpacity = useSharedValue(1);

  const screenWidth = Dimensions.get('window').width;
  const screenHeight = Dimensions.get('window').height;

  useEffect(() => {
    // 启动脉冲动画
    pulseOpacity.value = withRepeat(
      withTiming(0.8, { duration: 1000 }),
      -1,
      true
    );

    loadProcessData();
  }, []);

  const loadProcessData = async () => {
    try {
      setIsLoading(true);
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const mockProcessData: ProcessData = {
        title: '员工请假申请',
        applicant: '李小明',
        submitTime: '2024-01-15 14:30',
        currentNode: '部门经理审批',
        status: '审批中',
        nodes: [
          {
            id: 'start',
            name: '开始',
            type: 'start',
            status: 'completed',
            assignee: '',
            time: '',
            result: '',
            comment: '',
            x: 100,
            y: 200
          },
          {
            id: 'applicant',
            name: '申请人提交',
            type: 'user',
            status: 'completed',
            assignee: '李小明',
            time: '2024-01-15 14:30',
            result: '已提交',
            comment: '申请年假3天',
            x: 200,
            y: 200
          },
          {
            id: 'dept-manager',
            name: '部门经理审批',
            type: 'user',
            status: 'current',
            assignee: '张经理',
            time: '',
            result: '',
            comment: '',
            x: 350,
            y: 200
          },
          {
            id: 'hr',
            name: '人力资源审批',
            type: 'user',
            status: 'pending',
            assignee: '王HR',
            time: '',
            result: '',
            comment: '',
            x: 500,
            y: 200
          },
          {
            id: 'director',
            name: '总监审批',
            type: 'user',
            status: 'future',
            assignee: '刘总监',
            time: '',
            result: '',
            comment: '',
            x: 650,
            y: 200
          },
          {
            id: 'end',
            name: '结束',
            type: 'end',
            status: 'future',
            assignee: '',
            time: '',
            result: '',
            comment: '',
            x: 750,
            y: 200
          }
        ],
        connections: [
          { from: 'start', to: 'applicant' },
          { from: 'applicant', to: 'dept-manager' },
          { from: 'dept-manager', to: 'hr' },
          { from: 'hr', to: 'director' },
          { from: 'director', to: 'end' }
        ]
      };

      setProcessData(mockProcessData);
    } catch (error) {
      Alert.alert('错误', '加载流程数据失败');
    } finally {
      setIsLoading(false);
    }
  };

  const handleBackPress = () => {
    if (router.canGoBack()) {
      router.back();
    }
  };

  const handleZoomIn = () => {
    if (currentScale < 2) {
      setCurrentScale(prev => prev + 0.1);
    }
  };

  const handleZoomOut = () => {
    if (currentScale > 0.5) {
      setCurrentScale(prev => prev - 0.1);
    }
  };

  const handleZoomReset = () => {
    setCurrentScale(1);
    setCurrentTranslateX(0);
    setCurrentTranslateY(0);
  };

  const handleNodePress = (node: ProcessNode, event: any) => {
    const { locationX, locationY } = event.nativeEvent;
    const containerRect = {
      width: screenWidth - 32,
      height: 400,
    };

    setSelectedNode(node);
    
    // 计算tooltip位置
    let tooltipX = locationX - 100; // 大致居中
    let tooltipY = locationY - 120; // 显示在节点上方

    // 确保不超出容器边界
    if (tooltipX < 10) tooltipX = 10;
    if (tooltipX + 200 > containerRect.width - 10) {
      tooltipX = containerRect.width - 210;
    }
    if (tooltipY < 10) {
      tooltipY = locationY + 40; // 显示在节点下方
    }

    setTooltipPosition({ x: tooltipX, y: tooltipY });
    setIsNodeTooltipVisible(true);
  };

  const handleCloseTooltip = () => {
    setIsNodeTooltipVisible(false);
    setSelectedNode(null);
  };

  const getNodeStyle = (status: string) => {
    switch (status) {
      case 'completed':
        return styles.nodeCompleted;
      case 'current':
        return styles.nodeCurrent;
      case 'pending':
        return styles.nodePending;
      case 'future':
        return styles.nodeFuture;
      default:
        return styles.nodeFuture;
    }
  };

  const getLineStyle = (fromStatus: string, toStatus: string) => {
    if (fromStatus === 'completed' && (toStatus === 'current' || toStatus === 'pending' || toStatus === 'future')) {
      return styles.lineCompleted;
    } else if (fromStatus === 'current' && (toStatus === 'pending' || toStatus === 'future')) {
      return styles.lineCurrent;
    }
    return styles.lineDefault;
  };

  const panGesture = Gesture.Pan()
    .onBegin((event) => {
      if (event.numberOfTouches === 1) {
        panRef.current.isDragging = true;
        panRef.current.lastTouchX = event.absoluteX;
        panRef.current.lastTouchY = event.absoluteY;
      } else if (event.numberOfTouches === 2) {
        const touches = event.allTouches;
        panRef.current.lastTouchDistance = Math.sqrt(
          Math.pow(touches[0].absoluteX - touches[1].absoluteX, 2) +
          Math.pow(touches[0].absoluteY - touches[1].absoluteY, 2)
        );
      }
    })
    .onUpdate((event) => {
      if (event.numberOfTouches === 1 && panRef.current.isDragging) {
        const deltaX = event.absoluteX - panRef.current.lastTouchX;
        const deltaY = event.absoluteY - panRef.current.lastTouchY;
        
        setCurrentTranslateX(prev => prev + deltaX);
        setCurrentTranslateY(prev => prev + deltaY);
        
        panRef.current.lastTouchX = event.absoluteX;
        panRef.current.lastTouchY = event.absoluteY;
      } else if (event.numberOfTouches === 2) {
        const touches = event.allTouches;
        const currentDistance = Math.sqrt(
          Math.pow(touches[0].absoluteX - touches[1].absoluteX, 2) +
          Math.pow(touches[0].absoluteY - touches[1].absoluteY, 2)
        );
        
        const scaleFactor = currentDistance / panRef.current.lastTouchDistance;
        const newScale = currentScale * scaleFactor;
        
        if (newScale >= 0.5 && newScale <= 2) {
          setCurrentScale(newScale);
        }
        
        panRef.current.lastTouchDistance = currentDistance;
      }
    })
    .onEnd(() => {
      panRef.current.isDragging = false;
    });

  const pulseAnimatedStyle = useAnimatedStyle(() => {
    return {
      opacity: pulseOpacity.value,
    };
  });

  const renderFlowChart = () => {
    if (isLoading || !processData) {
      return (
        <View style={styles.loadingContainer}>
          <Animated.View style={[styles.loadingSpinner, pulseAnimatedStyle]} />
          <Text style={styles.loadingText}>加载流程图中...</Text>
        </View>
      );
    }

    return (
      <GestureDetector gesture={panGesture}>
        <View style={styles.flowContainer}>
          <Svg
            width="100%"
            height="400"
            viewBox="0 0 800 400"
            style={[
              styles.flowSvg,
              {
                transform: [
                  { scale: currentScale },
                  { translateX: currentTranslateX / currentScale },
                  { translateY: currentTranslateY / currentScale },
                ],
              },
            ]}
          >
            {/* 绘制连接线 */}
            {processData.connections.map((connection, index) => {
              const fromNode = processData.nodes.find(node => node.id === connection.from);
              const toNode = processData.nodes.find(node => node.id === connection.to);
              
              if (!fromNode || !toNode) return null;
              
              return (
                <Line
                  key={`connection-${index}`}
                  x1={fromNode.x + 20}
                  y1={fromNode.y}
                  x2={toNode.x - 20}
                  y2={toNode.y}
                  strokeWidth="2"
                  style={getLineStyle(fromNode.status, toNode.status)}
                />
              );
            })}

            {/* 绘制节点 */}
            {processData.nodes.map((node) => (
              <G key={node.id}>
                <TouchableOpacity
                  onPress={(event) => handleNodePress(node, event)}
                  activeOpacity={0.8}
                >
                  <Circle
                    cx={node.x}
                    cy={node.y}
                    r="20"
                    style={[
                      getNodeStyle(node.status),
                      node.status === 'current' && pulseAnimatedStyle,
                    ]}
                  />
                </TouchableOpacity>
                <SvgText
                  x={node.x}
                  y={node.y + 45}
                  textAnchor="middle"
                  fill="#9ca3af"
                  fontSize="12"
                >
                  {node.name}
                </SvgText>
              </G>
            ))}
          </Svg>
        </View>
      </GestureDetector>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={handleBackPress}
          activeOpacity={0.7}
        >
          <FontAwesome6 name="arrow-left" size={18} color="#d1d5db" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>审批流程</Text>
        <View style={styles.headerPlaceholder} />
      </View>

      <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
        {/* 审批基本信息 */}
        <LinearGradient
          colors={['rgba(99, 102, 241, 0.1)', 'rgba(139, 92, 246, 0.1)']}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
          style={styles.approvalInfoCard}
        >
          <View style={styles.approvalInfoHeader}>
            <Text style={styles.approvalTitle}>{processData?.title || ''}</Text>
            <View style={styles.statusBadge}>
              <Text style={styles.statusText}>{processData?.status || ''}</Text>
            </View>
          </View>
          <View style={styles.approvalInfoGrid}>
            <View style={styles.approvalInfoItem}>
              <Text style={styles.approvalInfoLabel}>申请人</Text>
              <Text style={styles.approvalInfoValue}>{processData?.applicant || ''}</Text>
            </View>
            <View style={styles.approvalInfoItem}>
              <Text style={styles.approvalInfoLabel}>发起时间</Text>
              <Text style={styles.approvalInfoValue}>{processData?.submitTime || ''}</Text>
            </View>
            <View style={styles.approvalInfoItem}>
              <Text style={styles.approvalInfoLabel}>当前节点</Text>
              <Text style={styles.approvalInfoValue}>{processData?.currentNode || ''}</Text>
            </View>
            <View style={styles.approvalInfoItem}>
              <Text style={styles.approvalInfoLabel}>流程状态</Text>
              <Text style={styles.approvalInfoValue}>进行中</Text>
            </View>
          </View>
        </LinearGradient>

        {/* 流程图区域 */}
        <View style={styles.flowChartSection}>
          <View style={styles.flowChartHeader}>
            <Text style={styles.flowChartTitle}>审批流程图</Text>
            <View style={styles.zoomControls}>
              <TouchableOpacity
                style={styles.zoomButton}
                onPress={handleZoomOut}
                activeOpacity={0.7}
              >
                <FontAwesome6 name="minus" size={14} color="#9ca3af" />
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.zoomButton}
                onPress={handleZoomReset}
                activeOpacity={0.7}
              >
                <FontAwesome6 name="house" size={14} color="#9ca3af" />
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.zoomButton}
                onPress={handleZoomIn}
                activeOpacity={0.7}
              >
                <FontAwesome6 name="plus" size={14} color="#9ca3af" />
              </TouchableOpacity>
            </View>
          </View>
          
          {renderFlowChart()}
        </View>

        {/* 图例说明 */}
        <View style={styles.legendSection}>
          <Text style={styles.legendTitle}>图例说明</Text>
          <View style={styles.legendGrid}>
            <View style={styles.legendItem}>
              <View style={[styles.legendDot, styles.nodeCompleted]} />
              <Text style={styles.legendText}>已完成</Text>
            </View>
            <View style={styles.legendItem}>
              <Animated.View style={[styles.legendDot, styles.nodeCurrent, pulseAnimatedStyle]} />
              <Text style={styles.legendText}>当前节点</Text>
            </View>
            <View style={styles.legendItem}>
              <View style={[styles.legendDot, styles.nodePending]} />
              <Text style={styles.legendText}>待处理</Text>
            </View>
            <View style={styles.legendItem}>
              <View style={[styles.legendDot, styles.nodeFuture]} />
              <Text style={styles.legendText}>后续节点</Text>
            </View>
          </View>
        </View>
      </ScrollView>

      {/* 节点信息浮层 */}
      <Modal
        visible={isNodeTooltipVisible}
        transparent={true}
        animationType="fade"
        onRequestClose={handleCloseTooltip}
      >
        <TouchableOpacity
          style={styles.tooltipOverlay}
          activeOpacity={1}
          onPress={handleCloseTooltip}
        >
          <View
            style={[
              styles.tooltip,
              {
                left: tooltipPosition.x,
                top: tooltipPosition.y,
              },
            ]}
          >
            <Text style={styles.tooltipTitle}>{selectedNode?.name || ''}</Text>
            <View style={styles.tooltipContent}>
              <View style={styles.tooltipRow}>
                <Text style={styles.tooltipLabel}>处理人：</Text>
                <Text style={styles.tooltipValue}>{selectedNode?.assignee || '无'}</Text>
              </View>
              <View style={styles.tooltipRow}>
                <Text style={styles.tooltipLabel}>处理时间：</Text>
                <Text style={styles.tooltipValue}>{selectedNode?.time || '未处理'}</Text>
              </View>
              <View style={styles.tooltipRow}>
                <Text style={styles.tooltipLabel}>处理结果：</Text>
                <Text style={styles.tooltipValue}>{selectedNode?.result || '待处理'}</Text>
              </View>
            </View>
            <View style={styles.tooltipCommentSection}>
              <Text style={styles.tooltipCommentLabel}>审批意见：</Text>
              <Text style={styles.tooltipComment}>{selectedNode?.comment || '无'}</Text>
            </View>
          </View>
        </TouchableOpacity>
      </Modal>
    </SafeAreaView>
  );
};

export default ApprovalFlowScreen;

